package com.sy.simpleegg.mvp.model

import com.google.gson.reflect.TypeToken
import com.sy.simpleegg.base.BaseModel
import com.sy.simpleegg.bean.BackscanPayParamLyySdk
import com.sy.simpleegg.bean.BackscanPayParamWhmHex
import com.sy.simpleegg.bean.CashDataWhmhex
import com.sy.simpleegg.bean.CashGoodBean
import com.sy.simpleegg.bean.CheckSaveCoinsResultBean
import com.sy.simpleegg.bean.CoinDataWhmhex
import com.sy.simpleegg.bean.CouponInfoBean
import com.sy.simpleegg.bean.GetWithdrawalCodeResult
import com.sy.simpleegg.bean.GoodBean
import com.sy.simpleegg.bean.GoodListBean
import com.sy.simpleegg.bean.LocalWithdrawalOrderBean
import com.sy.simpleegg.bean.PayCodeParamLyySdk
import com.sy.simpleegg.bean.PayCodeParamWhmMqtt
import com.sy.simpleegg.bean.PayCodeParamWhmMqttHex
import com.sy.simpleegg.bean.PayIconBean
import com.sy.simpleegg.bean.PayTypeData
import com.sy.simpleegg.bean.RepCashDataBean
import com.sy.simpleegg.bean.RepCashKkb
import com.sy.simpleegg.bean.RepCashLyysdk
import com.sy.simpleegg.bean.RepCashWhmhex
import com.sy.simpleegg.bean.RepCashYch
import com.sy.simpleegg.bean.RepCoinDataBean
import com.sy.simpleegg.bean.RepCoinKkb
import com.sy.simpleegg.bean.RepCoinWhmhex
import com.sy.simpleegg.bean.RepCoinYch
import com.sy.simpleegg.bean.RepWriteOffDataBean
import com.sy.simpleegg.bean.RepWriteOffKkb
import com.sy.simpleegg.bean.RepWriteOffWhm
import com.sy.simpleegg.bean.RepWriteOffYch
import com.sy.simpleegg.platform.lyysdk.bean.RecieveOrderLyySdkBean
import com.sy.simpleegg.bean.ReqBackscanPayBean
import com.sy.simpleegg.bean.ReqPayCodeBean
import com.sy.simpleegg.bean.ReqStartResultBean
import com.sy.simpleegg.bean.SaveCoinLoginBean
import com.sy.simpleegg.bean.SaveMoneyResult
import com.sy.simpleegg.bean.StartResultParamKkb
import com.sy.simpleegg.bean.StartResultParamLyyBox
import com.sy.simpleegg.bean.StartResultParamLyySdk
import com.sy.simpleegg.bean.StartResultParamWhmMqttHex
import com.sy.simpleegg.bean.StartResultParamYch
import com.sy.simpleegg.config.Config
import com.sy.simpleegg.constant.Constant
import com.sy.simpleegg.constant.PackageType
import com.sy.simpleegg.constant.PayState
import com.sy.simpleegg.constant.PayType
import com.sy.simpleegg.constant.ProductType
import com.sy.simpleegg.constant.SaveCoinStep
import com.sy.simpleegg.ext.logFile
import com.sy.simpleegg.mvp.contract.HomeContract
import com.sy.simpleegg.platform.BackstagePlatform
import com.sy.simpleegg.platform.kkb.bean.KkbBuyPackageBean
import com.sy.simpleegg.platform.kkb.bean.KkbGoodBean
import com.sy.simpleegg.platform.kkb.bean.RecieveOrderKkbBean
import com.sy.simpleegg.platform.kkb.bean.member.KkbQrCodeMemberInfoResponse
import com.sy.simpleegg.platform.lyysdk.bean.LyySdkGoodBean
import com.sy.simpleegg.platform.whm.bean.WhmGoodBean
import com.sy.simpleegg.platform.whmhex.bean.RecieveOrderWhmMqttHexBean
import com.sy.simpleegg.platform.whmhex.bean.WhmHexGoodBean
import com.sy.simpleegg.platform.ychsdk.bean.RecieveOrderYchBean
import com.sy.simpleegg.platform.ychsdk.bean.YchBuyPackageBean
import com.sy.simpleegg.platform.ychsdk.bean.YchBuyPackageItem
import com.sy.simpleegg.platform.ychsdk.bean.YchGoodBean
import com.sy.simpleegg.platform.ychsdk.bean.member.QrCodeMemberInfoResponse
import com.sy.simpleegg.room.CoinType
import com.sy.simpleegg.room.RoomUtil
import com.sy.simpleegg.room.entity.CoinEntity
import com.sy.simpleegg.room.entity.GoodEntity
import com.sy.simpleegg.room.entity.OrderEntity
import com.sy.simpleegg.room.entity.SaveCoinEntity
import com.sy.simpleegg.util.BigDecimalUtil
import com.sy.simpleegg.util.CommonUtil
import com.sy.simpleegg.util.DateTimeUtil
import com.sy.simpleegg.util.GsonUtil
import com.sy.simpleegg.util.Preference
import com.sy.mqhexsdk.bean.rec.RecUserInfoNew
import java.text.DecimalFormat

class HomeModel : BaseModel(), HomeContract.Model {

    private val df = DecimalFormat("#.00")
    private var cartList: MutableList<GoodEntity> = ArrayList()
    private var cartCount = 0
    private var cartAmount: String = "0"
    private var currentOrder: OrderEntity? = null

    private var selectGood: GoodBean? = null

    private var currentCashOrder: OrderEntity? = null

    private var cashGoodList: MutableList<CashGoodBean> = mutableListOf()

    /**
     * 接入第三方平台
     */
    private var p: BackstagePlatform by Preference(
        Constant.SETTING_OTHER_PLATFORM,
        BackstagePlatform.WHM_MQTT_HEX
    )

    /**
     * 国家地区
     */
    private var country: Int by Preference(Constant.SETTING_COUNTRY, Config.DEFAULT_COUNTRY_CODE)

    /**
     * 现金配置 lyy模板配置格式
     */
    private var cashConfigHex: String by Preference(Constant.SETTING_CASH_CONFIG, "0000000000000000000000000000000000000000")
    /**
     * lyybox二维码
     */
    private var lyyboxQrCode: String by Preference(Constant.SETTING_LYYBOX_QR_CODE, "")
    private var devNumber: String by Preference(Constant.SETTING_DEVICE_NUMBER, "")

    override fun getPackage() {

    }

    override suspend fun saveGoods(platform: BackstagePlatform, dataList: Any): GoodListBean? {
        return try {
            val goodEntity = GoodEntity().apply {
                this.platform = platform
                goodDetial = GsonUtil.getInstance()?.toJson(dataList) ?: ""
                time = DateTimeUtil.nowDateTime
            }
            RoomUtil.insertGood(mutableListOf(goodEntity))
            val result = RoomUtil.getLastGood(platform)
            if (result.isNullOrEmpty()) {
                null
            } else {
//                result[0]
                getFinalGoods(result[0])
            }
        } catch (e: Exception) {
            e.printStackTrace()
            logFile("保存套餐数据异常：${e.message}")
            null
        }
    }

    override suspend fun getPayCode(goodBean: GoodBean, payTypeData: PayTypeData?): ReqPayCodeBean? {
        return try {
            val k = CommonUtil.getUuid()
            val p = goodBean.platform
            selectGood = goodBean.apply {
                this.k = k
            }
            val order = OrderEntity().apply {
                uuid = k
                amount = goodBean.amount
                money = goodBean.money
                platform = goodBean.platform
                goodId = goodBean.goodId
                goodType = goodBean.goodType
            }
            RoomUtil.orderInsert(order)

            var iconType = 0
            var payName = ""
            var payIcon = ""
            val reqData = when (p) {
                BackstagePlatform.DEF_MQTT -> {
                    null
                }

                BackstagePlatform.LYY_SDK -> {
                    val goodData = "${goodBean.goodId},${goodBean.amount},${goodBean.money}"
                    val type = when (goodBean.goodType) {
                        PackageType.NORMAL -> "0"
                        PackageType.RECHARGE -> "1"
                        PackageType.CASH -> "2"
                    }
                    iconType = 1
                    PayCodeParamLyySdk(goodData, type, k)
                }

                BackstagePlatform.LYY_BOX -> {
                    null
                }
                BackstagePlatform.WHM_MQTT -> {
                    val pkgType = when (goodBean.goodType){
                        PackageType.NORMAL -> 1
                        PackageType.RECHARGE -> 2
                        PackageType.CASH -> 2
                    }
                    PayCodeParamWhmMqtt(goodBean.goodId.toInt(16), payTypeData?.code!!, pkgType)
                }

                BackstagePlatform.WHM_MQTT_HEX -> {
                    val pkgType = when (goodBean.goodType){
                        PackageType.NORMAL -> 1
                        PackageType.RECHARGE -> 2
                        PackageType.CASH -> 2
                    }
                    iconType = 2
                    payName = payTypeData!!.name
                    payIcon = payTypeData!!.icon
                    PayCodeParamWhmMqttHex(goodBean.goodId, payTypeData?.code!!, pkgType)
//                    PayCodeParamWhmMqttHex(goodBean.goodId, if (country == 1) 0 else payTypeData?.code!!, pkgType)//新接口
                }

                BackstagePlatform.YCH_SDK -> {

                }

                BackstagePlatform.KKB -> {

                }
            }
            ReqPayCodeBean(p, k, goodBean, reqData, PayIconBean(iconType, payName, payIcon))
        } catch (e: Exception) {
            e.printStackTrace()
            logFile("保存订单数据异常：${e.message}")
            null
        }
    }

    override suspend fun checkOrder(order: OrderEntity, isCash: Boolean): OrderEntity? {
        return try {
            var isSavedOrder = true
            val p = order.platform
            val k = order.uuid
            val pk = order.payUuid
            var lastOrder: OrderEntity? = null
            if (isCash) {
//                val cashOrderList = getLastCashOrder(p)
                val cashOrderList = RoomUtil.orderGetByUuid(k)
                lastOrder = cashOrderList?.run {
                    if (this.isEmpty()) {
                        null
                    } else {
                        this[0]
                    }
                }
            } else {
                val normalOrderList = getLastNormalOrder(p)
                lastOrder = normalOrderList?.run {
                    if (this.isEmpty()) {
                        isSavedOrder = false
                        RoomUtil.orderInsert(order)
                        order
//                        RoomUtil.orderGetByUuid(k)?.let {
//                            if (it.isEmpty()){
//                                order
//                            }else{
//                                it[0]
//                            }
//                        }
//                        getLastNormalOrder(p)?.let {
//                            it[0]
//                        }
                    } else {
                        this[0]
                    }
                }
            }
            lastOrder?.let {
                when (p) {
                    BackstagePlatform.LYY_SDK -> {
                        if (it.amount == order.amount && it.money == order.money) {
                            it.payUuid = pk
                            RoomUtil.orderUpdate(it)
                            if (isCash) {
                                it
                            } else {
                                RoomUtil.orderNormalLast(p)?.let { item ->
                                    item[0]
                                }
                            }
                        } else {
                            logFile("lyy_sdk 没有此订单 uuid=${order.uuid} payUuid=${order.payUuid}")
                            null
                        }
                    }
                    BackstagePlatform.YCH_SDK -> {
                        RoomUtil.orderGetByUuid(k)?.let { orderList ->
                            if (orderList.isEmpty()){
                                return null
                            }
                            orderList[0]
                        }
                    }

                    BackstagePlatform.KKB -> {
                        RoomUtil.orderGetByUuid(k)?.let { orderList ->
                            if (orderList.isEmpty()){
                                return null
                            }
                            orderList[0]
                        }
                    }
                    else -> {
//                        if (k == it.uuid) it else null
                        if (!isSavedOrder && order.money == "0"){
                            //更新为派币订单
                            it.payType = PayType.PAIBI
                            RoomUtil.orderUpdatePayType(it.uuid, PayType.PAIBI)
//                            RoomUtil.orderUpdate(it)
                            RoomUtil.orderGetByUuid(it.uuid)?.let {
                                logFile("更新后订单数据：${GsonUtil.getInstance()?.toJson(it)}")
                                it[0]
                            }
                        }else {
                            it
                        }
                    }
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
            logFile("获取订单 ${order.uuid} 异常：${e.message}")
            null
        }

    }

    override suspend fun checkOrderByCoins(order: OrderEntity, isCash: Boolean): OrderEntity? {
        return try {
            var isSavedOrder = true
            val p = order.platform
            val k = order.uuid
            val pk = order.payUuid
            var lastOrder: OrderEntity? = null
            if (isCash) {
//                val cashOrderList = getLastCashOrder(p)
                val cashOrderList = RoomUtil.orderGetByUuid(k)
                lastOrder = cashOrderList?.run {
                    if (this.isEmpty()) {
                        null
                    } else {
                        this[0]
                    }
                }
            } else {
                val normalOrderList = RoomUtil.orderNormalAmountLast(p, order.amount)
                lastOrder = normalOrderList?.run {
                    if (this.isEmpty()) {
                        isSavedOrder = false
                        RoomUtil.orderInsert(order)
                        order
//                        RoomUtil.orderGetByUuid(k)?.let {
//                            if (it.isEmpty()){
//                                order
//                            }else{
//                                it[0]
//                            }
//                        }
//                        getLastNormalOrder(p)?.let {
//                            it[0]
//                        }
                    } else {
                        this[0]
                    }
                }
            }
            lastOrder?.let {
                when (p) {
                    BackstagePlatform.LYY_SDK -> {
                        if (it.amount == order.amount && it.money == order.money) {
                            it.payUuid = pk
                            RoomUtil.orderUpdate(it)
                            if (isCash) {
                                it
                            } else {
                                RoomUtil.orderNormalLast(p)?.let { item ->
                                    item[0]
                                }
                            }
                        } else {
                            logFile("lyy_sdk 没有此订单 uuid=${order.uuid} payUuid=${order.payUuid}")
                            null
                        }
                    }
                    BackstagePlatform.YCH_SDK -> {
                        RoomUtil.orderGetByUuid(k)?.let { orderList ->
                            if (orderList.isEmpty()){
                                return null
                            }
                            orderList[0]
                        }
                    }

                    BackstagePlatform.KKB -> {
                        RoomUtil.orderGetByUuid(k)?.let { orderList ->
                            if (orderList.isEmpty()){
                                return null
                            }
                            orderList[0]
                        }
                    }
                    else -> {
//                        if (k == it.uuid) it else null
                        if (!isSavedOrder && order.money == "0"){
                            //更新为派币订单
                            it.payType = PayType.PAIBI
                            RoomUtil.orderUpdatePayType(it.uuid, PayType.PAIBI)
//                            RoomUtil.orderUpdate(it)
                            RoomUtil.orderGetByUuid(it.uuid)?.let {
                                logFile("更新后订单数据：${GsonUtil.getInstance()?.toJson(it)}")
                                it[0]
                            }
                        }else {
                            it
                        }
                    }
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
            logFile("获取订单 ${order.uuid} 异常：${e.message}")
            null
        }
    }

    override suspend fun setOrderTimeout(k: String) {
        RoomUtil.orderUpdateByUuid(k, PayState.TIMEOUT)
    }

    override suspend fun postResult(
        platform: BackstagePlatform,
        k: String,
        success: Boolean,
        money: String,
        realOutCoins: Long,
        needCoins: Long,
        isMqOrder: Boolean,
        isWriteOff: Boolean,
        isWithdrawal: Boolean,
        isCash: Boolean,
        uid: String
    ): ReqStartResultBean? {
        return try {
            val reqData = when (platform) {
                BackstagePlatform.DEF_MQTT -> {
                    null
                }

                BackstagePlatform.LYY_SDK -> {

                    StartResultParamLyySdk(
                        if (success) 0 else 1,
                        if (success) "" else "设备故障",
                        k
                    )
                }

                BackstagePlatform.LYY_BOX -> {
                    StartResultParamLyyBox(
                        if (success) 1 else 0,
                        if (success) "" else "设备故障",
                        k
                    )
                }

                BackstagePlatform.WHM_MQTT -> {
                    null
                }

                BackstagePlatform.WHM_MQTT_HEX -> {
                    StartResultParamWhmMqttHex(
                        if (success) 1 else 2,
                        if (success) 0 else 1,
                        "",
                        k,
                        realOutCoins,
                        needCoins,
                        isWithdrawal
                    )
                }

                BackstagePlatform.YCH_SDK -> {
                    StartResultParamYch(
                        if (success) 0 else 1,
                        realOutCoins.toInt(),
                        needCoins.toInt(),
                        -1L,
                        k,
                        k,
                        isMqOrder,
                        isWriteOff
                    )
                }

                BackstagePlatform.KKB -> {
                    StartResultParamKkb(
                        isCash,
                        if (success) 0 else 1,
                        k,
                        money,
                        needCoins.toInt(),
                        realOutCoins.toInt(),
                        "",
                        -1,
                        uid
                    )
                }
            }
            ReqStartResultBean(platform, k, reqData)
        } catch (e: Exception) {
            e.printStackTrace()
            logFile("上报启动结果请求数据异常：${e.message}")
            null
        }
    }

    override suspend fun outCoins(coins: Long) {
        try {
            val coinEntity = CoinEntity().apply {
                type = CoinType.OUT
                this.coins = coins
                date = DateTimeUtil.nowDate
                time = DateTimeUtil.nowTime
            }
            RoomUtil.saveCoins(coinEntity)
        } catch (e: Exception) {
            e.printStackTrace()
            logFile("保存出币数异常：${e.message}")
        }
    }

    override fun clearSelectGood() {
        selectGood = null
    }

    override suspend fun postBackscanData(type: Int, scanData: String, goodBean: GoodBean?, scanDataType: String): ReqBackscanPayBean? {
        return try {
            if (selectGood != null) {
                //付款码数据上报
                selectGood?.let {
                    val p = it.platform
                    val k = it.k
                    val postData = when (it.platform) {
                        BackstagePlatform.DEF_MQTT -> {
                            return null
                        }

                        BackstagePlatform.LYY_SDK -> {
                            val goodData = "${it.goodId},${it.amount},${it.money}"
                            val type = when (it.goodType) {
                                PackageType.NORMAL -> "0"
                                PackageType.RECHARGE -> "1"
                                PackageType.CASH -> "2"
                            }
                            BackscanPayParamLyySdk(goodData, type, scanData, k)
                        }

                        BackstagePlatform.LYY_BOX -> {
                            return null
                        }

                        BackstagePlatform.WHM_MQTT -> {
                            return null
                        }

                        BackstagePlatform.WHM_MQTT_HEX -> {
                            BackscanPayParamWhmHex().apply {
                                data = scanData
                                pkgType = when (it.goodType) {
                                    PackageType.NORMAL -> 1
                                    PackageType.RECHARGE -> 2
                                    else -> 1
                                }
                                pkgId = it.goodId
                                payType = type
                            }
                        }

                        BackstagePlatform.YCH_SDK -> {
                            goodBean?.let { gb ->
                                YchBuyPackageBean(BigDecimalUtil.getPrice(gb.money)!!, gb.amount.toInt(), scanDataType, scanData,
                                    k, devNumber, listOf(YchBuyPackageItem(gb.goodId, 1))
                                )
                            }
                        }

                        BackstagePlatform.KKB -> {
                            goodBean?.let { gb ->
                                KkbBuyPackageBean(when (Config.PRODUCT_TYPE){
                                    ProductType.CURRENCY -> 2
                                    ProductType.BEAD -> 1
                                },
                                    k,
                                    gb.money,
                                    gb.amount.toInt(),
                                    when (scanDataType){
                                        "WeChatCodePay" -> 1
                                        "AlipayCodePay" -> 2
                                        else -> 1
                                    }).apply {
                                        if (scanData.isNotEmpty()){
                                            payCode = scanData
                                        }
                                        if (payType == 3) {
                                            payMoneyCent = gb.money
                                        }else{
                                            packageId = gb.goodId
                                        }
                                }
//                                KkbBuyPackageBean(BigDecimalUtil.getPrice(gb.money)!!, gb.amount.toInt(), scanDataType, scanData,
//                                    k, devNumber, listOf(KkbBuyPackageItem(gb.goodId, 1))
//                                )
                            }
                        }
                    }
                    ReqBackscanPayBean(p, k, postData)
                }
            }else{
                //核销数据上报
                val postData = when (p){
                    BackstagePlatform.DEF_MQTT -> {
                        null
                    }
                    BackstagePlatform.LYY_SDK -> {
                        null
                    }
                    BackstagePlatform.LYY_BOX -> {
                        null
                    }
                    BackstagePlatform.WHM_MQTT -> {
                        null
                    }
                    BackstagePlatform.WHM_MQTT_HEX -> {
                        BackscanPayParamWhmHex().apply {
                            verificationType = type
                            data = scanData
                        }
                    }

                    BackstagePlatform.YCH_SDK -> {
                        null
                    }

                    BackstagePlatform.KKB -> {
                        goodBean?.let { gb ->
                            //创建订单
                            val k = CommonUtil.getUuid()
//                            val p = gb.platform
//                            selectGood = gb.apply {
//                                this.k = k
//                            }
//                            val order = OrderEntity().apply {
//                                uuid = k
//                                amount = gb.amount
//                                money = gb.money
//                                platform = p
//                                goodId = gb.goodId
//                                goodType = gb.goodType
//                            }
//                            RoomUtil.orderInsert(order)

                            val reqdata = KkbBuyPackageBean(when (Config.PRODUCT_TYPE){
                                ProductType.CURRENCY -> 2
                                ProductType.BEAD -> 1
                            },
                                k.replace("-", ""),
                                gb.money,
                                gb.amount.toInt(),
                                when (scanDataType){
                                    "WeChatCodePay" -> 1
                                    "AlipayCodePay" -> 2
                                    else -> 1
                                }).apply {
                                if (scanData.isNotEmpty()){
                                    payCode = scanData
                                }
                                if (payType == 3) {
                                    payMoneyCent = gb.money
                                }else{
                                    packageId = gb.goodId
                                }
                            }
                            return ReqBackscanPayBean(p, k, reqdata)
//                                KkbBuyPackageBean(BigDecimalUtil.getPrice(gb.money)!!, gb.amount.toInt(), scanDataType, scanData,
//                                    k, devNumber, listOf(KkbBuyPackageItem(gb.goodId, 1))
//                                )
                        }
                    }
                }
                ReqBackscanPayBean(p, "", postData)
            }
        } catch (e: Exception) {
            e.printStackTrace()
            logFile("处理反扫支付数据异常：${e.message}")
            null
        }
    }

    override suspend fun getCashGoods(platform: BackstagePlatform): MutableList<CashGoodBean>? {
        return try {
            //刷新纸钞套餐数据
            val channelDenominations = CommonUtil.getChannelMode(country).split(";")[0].split(",")
            val cashConfig = cashConfigHex
            val channelCoins: MutableList<String> = mutableListOf()
            for (i in cashConfig.indices step 4){
                val coins = "${cashConfig.substring(i + 2, i + 4)}${cashConfig.substring(i, i + 2)}".toLong(16)
                channelCoins.add(coins.toString())
            }
            val cashGoodBeanList: MutableList<CashGoodBean> = mutableListOf()
            channelCoins.forEachIndexed { index, coins ->
                val denomination = channelDenominations[index]
                if (denomination.isEmpty() || denomination == "0" || denomination.toLong() < 0){
                    return@forEachIndexed
                }
                if (coins.isEmpty() || coins == "0" || coins.toLong() < 0){
                    return@forEachIndexed
                }
                cashGoodBeanList.add(CashGoodBean("$index", denomination, coins, "0", index))
            }
            logFile("纸钞套餐：${GsonUtil.getInstance()?.toJson(cashGoodBeanList)}")

            cashGoodList = cashGoodBeanList
            cashGoodBeanList
        } catch (e: Exception) {
            e.printStackTrace()
            logFile("获取纸钞套餐异常：${e.message}")
            null
        }
    }

    override suspend fun cashPayOut(
        platform: BackstagePlatform,
        money: String,
        coins: String
    ): RepCashDataBean? {
        return try {
            if (money == "0" && coins == "0") {
                return null
            }
//            val uuid = CommonUtil.getUuid()
//            val order = OrderEntity().apply {
//                this.uuid = uuid
//                amount = coins
//                this.money = money
//                this.platform = platform
//                goodType = PackageType.CASH
//                date = DateTimeUtil.nowDate
//                isPay = PayState.SUCCESS
//            }
//            RoomUtil.orderInsert(order)
//            val currentOrder = RoomUtil.orderGetByUuid(uuid)

            var uuid = ""
            var moneyList = ""
            if (currentCashOrder != null){
                uuid = currentCashOrder!!.uuid
                moneyList = currentCashOrder!!.moneyList
                currentCashOrder!!.isPay = PayState.SUCCESS
                RoomUtil.orderUpdate(currentCashOrder!!)
            }else{
                uuid = CommonUtil.getUuid()
                val order = OrderEntity().apply {
                    this.uuid = uuid
                    amount = coins
                    this.money = money
                    this.platform = platform
                    goodType = PackageType.CASH
                    payType = PayType.CASH
                    isPay = PayState.SUCCESS
                }
                RoomUtil.orderInsert(order)
            }

            logFile("纸钞订单：${GsonUtil.getInstance()!!.toJson(currentCashOrder)}")
            createCashOrder(platform, uuid, money, coins, moneyList)
        } catch (e: Exception) {
            e.printStackTrace()
            logFile("保存现金订单异常：${e.message}")
            null
        }
    }

    override suspend fun localWithdrawalOut(
        platform: BackstagePlatform,
        uid: String,
        coins: String,
    ): LocalWithdrawalOrderBean{
        return try {
            if (coins == "0") {
                return LocalWithdrawalOrderBean(null)
            }

            val uuid = CommonUtil.getUuid()
            val order = OrderEntity().apply {
                this.uuid = uuid
                orderNumber = uuid
                amount = coins
                this.money = "0"
                this.platform = platform
                goodType = PackageType.NORMAL
                payType = PayType.WITHDRAWAL
                isPay = PayState.SUCCESS
                info2 = uid
            }
            RoomUtil.orderInsert(order)

            logFile("本地提币订单：${GsonUtil.getInstance()!!.toJson(order)}")
            val orderData = when (platform){
                BackstagePlatform.DEF_MQTT -> null
                BackstagePlatform.LYY_SDK -> null
                BackstagePlatform.LYY_BOX -> null
                BackstagePlatform.WHM_MQTT -> null
                BackstagePlatform.WHM_MQTT_HEX -> null
                BackstagePlatform.YCH_SDK -> null
                BackstagePlatform.KKB -> {
                    RecieveOrderKkbBean(uuid, "0", coins, uuid, uuid, false, false)
                }
            }
            LocalWithdrawalOrderBean(orderData)
        } catch (e: Exception) {
            e.printStackTrace()
            logFile("保存本地提币订单异常：${e.message}")
            LocalWithdrawalOrderBean(null)
        }
    }

    override suspend fun getLastCashOrder(platform: BackstagePlatform): MutableList<OrderEntity>? {
        return try {
            RoomUtil.orderCashLast(platform)
        } catch (e: Exception) {
            e.printStackTrace()
            logFile("获取最新纸钞订单异常：${e.message}")
            null
        }
    }

    override suspend fun getLastNormalOrder(platform: BackstagePlatform): MutableList<OrderEntity>? {
        return try {
            RoomUtil.orderNormalLast(platform)
        } catch (e: Exception) {
            e.printStackTrace()
            logFile("获取最新普通订单异常：${e.message}")
            null
        }
    }

    override suspend fun getLastRechargeOrder(platform: BackstagePlatform): MutableList<OrderEntity>? {
        return try {
            RoomUtil.orderRechargeLast(platform)
        } catch (e: Exception) {
            e.printStackTrace()
            logFile("获取最新普通订单异常：${e.message}")
            null
        }
    }

    override fun setCurrentCashOrder(cashOrder: OrderEntity?) {
        currentCashOrder = cashOrder
    }

    override suspend fun saveMoney(
        checkMoney: Long,
        totalMoney: Long,
    ): SaveMoneyResult? {
        return try {
            val cMoney = checkMoney * 100L
            val tMoney = totalMoney * 100L
            val orderNumber =  currentCashOrder?.uuid ?: CommonUtil.getUuid()
            var moneyListStr = currentCashOrder?.moneyList ?: ""

            if (moneyListStr.isEmpty()){
                //直接创建面额数据 "100,1;"
                moneyListStr = "$cMoney,1;"
            }else{
                val newList: MutableList<String> = mutableListOf()
                val tempList = moneyListStr.split(";")
                tempList.forEach{ temp ->
                    if (temp.isNotEmpty()){
                        val items = temp.split(",")
                        val money = items[0]
                        var quantity = items[1].toInt()
                        if (money == cMoney.toString()){
                            quantity ++
                        }
                        val newItem = "$money,$quantity;"
                        newList.add(newItem)
                    }
                }

                moneyListStr = ""
                newList.forEach {
                    moneyListStr += it
                }
            }

            val coins = calculateCoins(cashGoodList, tMoney)

//            val coins = run coins@{
//                CommonUtil.getChannelMode(country).split(";")[0].split(",").forEachIndexed { index, denominationStr ->
//                    val denomination = denominationStr.toLong()
//                    if (denomination <= 0){
//                        return@forEachIndexed
//                    }
//                    if (denomination == tMoney){
//                        return@coins "${cashConfigHex.substring(index*4 + 2, (index + 1)*4)}${cashConfigHex.substring(index*4, index*4 + 2)}".toLong(16).toString()
//                    }
//                }
//                "0"
//            }

            val uuid = if (currentCashOrder == null){
                val uuid = CommonUtil.getUuid()
                val order = OrderEntity().apply {
                    this.uuid = uuid
                    amount = coins.toString()
                    money = tMoney.toString()
                    moneyList = moneyListStr
                    platform = p
                    goodType = PackageType.CASH
                    payType = PayType.CASH
                    isPay = PayState.UNPAYED
                }
                RoomUtil.orderInsert(order)
                currentCashOrder = RoomUtil.orderCashLast(p)?.get(0)
                uuid
            }else{
                currentCashOrder!!.amount = coins.toString()
                currentCashOrder!!.money = tMoney.toString()
                currentCashOrder!!.moneyList = moneyListStr
                RoomUtil.orderUpdate(currentCashOrder!!)
                currentCashOrder!!.uuid
            }
            SaveMoneyResult(coins > 0, createCashOrder(p, uuid, tMoney.toString(), coins.toString(), moneyListStr), uuid, tMoney, coins)
        }catch (e: Exception){
            e.printStackTrace()
            logFile("获取最新纸钞订单异常：${e.message}")
            SaveMoneyResult(false, null, "", totalMoney*100L, 0)
        }
    }

    override suspend fun saveOrder(order: OrderEntity) {
        try {
            RoomUtil.orderInsert(order)
        } catch (e: Exception) {
            e.printStackTrace()
            logFile("保存订单异常：${e.message}")
        }
    }

    override suspend fun loadCoins(): String {
        return try {
            RoomUtil.getLastCoin()?.let { coinList ->
                if (coinList.isEmpty()) {
                    "0"
                } else {
                    coinList[0].remainCoin.toString()
                }
            } ?: "0"
        } catch (e: Exception) {
            e.printStackTrace()
            logFile("获取设备余币异常：${e.message}")
            "err"
        }
    }

    override suspend fun refreshPayCode(data: String): String {
        return try {
            when (p){
                BackstagePlatform.DEF_MQTT -> data
                BackstagePlatform.LYY_SDK -> data
                BackstagePlatform.LYY_BOX -> data
                BackstagePlatform.WHM_MQTT -> data
                BackstagePlatform.WHM_MQTT_HEX -> {
                    var sn = ""
                    var codeData = ""
                    if (data.contains(",") && data.startsWith(",")){
                        codeData = data.substring(1)
                    }else if (data.contains(",") && !data.startsWith(",")){
                        sn = data.split(",")[0]
                        val orderList = RoomUtil.orderNormalLast(p)
                        orderList?.let {
                            it[0].uuid = sn
                            it[0].orderNumber = sn
                            RoomUtil.orderUpdate(it[0])
                            val lastOrder = RoomUtil.orderNormalLast(p)!![0]
                        }
                        codeData = data.split(",")[1]
                    }else{
                        codeData = data
                    }
                    codeData
//                    val sn = data.split(",")[0]
//                    val orderList = RoomUtil.orderNormalLast(p)
//                    orderList?.let {
//                        it[0].uuid = sn
//                        it[0].orderNumber = sn
//                        RoomUtil.orderUpdate(it[0])
//                        val lastOrder = RoomUtil.orderNormalLast(p)!![0]
//                    }
//                    data.split(",")[1]
                }

                BackstagePlatform.YCH_SDK -> {
//                    val transId = data.split(",")[0]
//                    val orderId = data.split(",")[1]
//                    val orderNumber = data.split(",")[2]
//                    val codeData = data.split(",")[3]
//
//                    val orderList = RoomUtil.orderGetByUuid(transId)
//                    orderList?.let {
//                        it[0].uuid = orderNumber
//                        it[0].orderNumber = orderNumber
//                        it[0].payUuid = orderId
//                        RoomUtil.orderUpdate(it[0])
//                    }
                    data
                }

                BackstagePlatform.KKB -> {
                    data
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
            logFile("处理正扫支付二维码异常：${e.message}")
            data
        }
    }

    override suspend fun updateResult(uuid: String, realCoins: String, result: PayState) {
        try {
            logFile("更新出币数 realCoins=$realCoins")
            RoomUtil.updateOrderRealCoins(uuid, realCoins)
            RoomUtil.orderUpdateByUuid(uuid, result)
        }catch (e: Exception){
            e.printStackTrace()
            logFile("更新订单结果异常：${e.message}")
        }
    }

    override suspend fun updateOrder(order: OrderEntity) {
        try {
            RoomUtil.orderUpdate(order)
        }catch (e: Exception){
            e.printStackTrace()
            logFile("更新订单异常：${e.message}")
        }
    }

    override suspend fun insertSaveCoin(userInfo: Any): SaveCoinLoginBean? {
        return try {
            val orderNumber = DateTimeUtil.nowDateTimeSp
            val userId = when (p){
                BackstagePlatform.DEF_MQTT -> ""
                BackstagePlatform.LYY_SDK -> ""
                BackstagePlatform.LYY_BOX -> ""
                BackstagePlatform.WHM_MQTT -> ""
                BackstagePlatform.WHM_MQTT_HEX -> {
                    val info = userInfo as RecUserInfoNew
                    info.userId
                }
                BackstagePlatform.YCH_SDK -> {
                    val info = userInfo as QrCodeMemberInfoResponse
                    info.LgInfo?.LeaguerID?:""
                }
                BackstagePlatform.KKB -> {
                    val info = userInfo as KkbQrCodeMemberInfoResponse
                    info.displayId?:""
                }
            }
            RoomUtil.insertSaveCoin(SaveCoinEntity().apply {
                sn = orderNumber
                uid = userId
            })
            SaveCoinLoginBean(orderNumber, userId, userInfo)
        }catch (e: Exception){
            e.printStackTrace()
            logFile("插入存币订单异常：${e.message}")
            null
        }
    }

    override suspend fun refreshSaveCoins(orderNumber: String, coins: String) {
        try {
            RoomUtil.updateSaveCoin(orderNumber, coins)
        }catch (e: Exception){
            e.printStackTrace()
            logFile("更新存币订单数据异常：${e.message}")
        }
    }

    override suspend fun checkSaveCoins(orderNumber: String, userId: String, transId: String, coinsStr: String): CheckSaveCoinsResultBean {
        return try {
            val saveCoins = coinsStr.toLong()
            var coins = 0L
            val result = RoomUtil.getSaveCoinBySn(orderNumber)?.run {
                logFile("获取存币订单数据：${GsonUtil.getInstance()?.toJson(this)}")
                if (isNullOrEmpty()){
                    false
                }else{
                    coins = this[0].coins.toLong()
                    RoomUtil.updateSaveCoinStep(orderNumber, SaveCoinStep.FINISH)
                    coins > 0 || saveCoins > 0
                }
            }?: false

            val finalCoins = if (saveCoins > coins) saveCoins else coins

            val repData = when(p){
                BackstagePlatform.DEF_MQTT -> null
                BackstagePlatform.LYY_SDK -> null
                BackstagePlatform.LYY_BOX -> null
                BackstagePlatform.WHM_MQTT -> null
                BackstagePlatform.WHM_MQTT_HEX -> {
                    RepCoinWhmhex(userId, mutableListOf(CoinDataWhmhex(1, 1, finalCoins)))
                }
                BackstagePlatform.YCH_SDK -> {
                    RepCoinYch(userId, finalCoins, "", transId)
                }
                BackstagePlatform.KKB -> {
                    RepCoinKkb(userId, finalCoins, "", transId)
                }
            }

            CheckSaveCoinsResultBean(result, RepCoinDataBean(p, orderNumber, repData))
        }catch (e: Exception){
            e.printStackTrace()
            logFile("校验存币订单数据异常：${e.message}")
            CheckSaveCoinsResultBean(false, null)
        }
    }

    override suspend fun getWithdrawalOrder(orderNumber: String): OrderEntity? {
        return try {
            RoomUtil.orderWithdrawalByOrderNumber(orderNumber)?.run {
                if (isNullOrEmpty()){
                    null
                }else{
                    this[0]
                }
            }
        }catch (e: Exception){
            e.printStackTrace()
            null
        }
    }

    override suspend fun getWriteOffOrder(orderNumber: String): OrderEntity? {
        return try {
            RoomUtil.orderWriteOffByOrderNumber(orderNumber)?.run {
                if (isNullOrEmpty()){
                    null
                }else{
                    this[0]
                }
            }
        }catch (e: Exception){
            e.printStackTrace()
            null
        }
    }

    override suspend fun getWithdrawalCode(platform: BackstagePlatform): GetWithdrawalCodeResult {
        return try {
            when (platform){
                BackstagePlatform.DEF_MQTT -> GetWithdrawalCodeResult(false)
                BackstagePlatform.LYY_SDK -> GetWithdrawalCodeResult(true, lyyboxQrCode)
                BackstagePlatform.LYY_BOX -> GetWithdrawalCodeResult(true, lyyboxQrCode)
                BackstagePlatform.WHM_MQTT -> GetWithdrawalCodeResult(false)
                BackstagePlatform.WHM_MQTT_HEX -> GetWithdrawalCodeResult(false)
                BackstagePlatform.YCH_SDK -> GetWithdrawalCodeResult(false)
                BackstagePlatform.KKB -> GetWithdrawalCodeResult(false)
            }
        }catch (e: Exception){
            e.printStackTrace()
            GetWithdrawalCodeResult(false)
        }
    }

    override suspend fun getMultCouponChannel(platform: BackstagePlatform): MutableList<CouponInfoBean>? {
        return try {
            when (platform){
                BackstagePlatform.DEF_MQTT -> null
                BackstagePlatform.LYY_SDK -> null
                BackstagePlatform.LYY_BOX -> null
                BackstagePlatform.WHM_MQTT -> null
                BackstagePlatform.WHM_MQTT_HEX -> {
                    mutableListOf(
                        CouponInfoBean("优惠券核销", -1, "WHM", 0, null, null, true),
                        CouponInfoBean("抖音核销", -1, "Titok", 1, null, null),
                        CouponInfoBean("美团核销", -1, "Meituan", 2, null, null),
                    )
                }
                BackstagePlatform.YCH_SDK -> {
                    mutableListOf(
                        CouponInfoBean("美团", -1, "Meituan", 0, null, null, true),
                        CouponInfoBean("抖音", -1, "Titok", 1, null, null),
                        CouponInfoBean("快手", -1, "KuaiShou", 2, null, null),
                        CouponInfoBean("口碑", -1, "Koubei", 3, null, null),
                    )
                }
                BackstagePlatform.KKB -> {
                    mutableListOf(
                        CouponInfoBean("美团", -1, "Meituan", 0, null, null, true),
                        CouponInfoBean("抖音", -1, "Titok", 1, null, null),
                        CouponInfoBean("快手", -1, "KuaiShou", 2, null, null),
                        CouponInfoBean("口碑", -1, "Koubei", 3, null, null),
                    )
                }
            }
        }catch (e: Exception){
            e.printStackTrace()
            null
        }
    }

    override suspend fun repWiteOffData(
        platform: BackstagePlatform,
        channel: String,
        codeData: String,
    ): RepWriteOffDataBean? {
        return try {
            when (platform){
                BackstagePlatform.DEF_MQTT -> null
                BackstagePlatform.LYY_SDK -> null
                BackstagePlatform.LYY_BOX -> null
                BackstagePlatform.WHM_MQTT -> null
                BackstagePlatform.WHM_MQTT_HEX -> {
                    RepWriteOffDataBean(platform, RepWriteOffWhm(codeData, when (channel){
                                                                                   "WHM" ->     "1"
                                                                                   "Titok" ->     "2"
                                                                                   "Meituan" ->     "3"
                                                                                   else ->     "1"
                                                                                         }, 1)
                    )
                }
                BackstagePlatform.YCH_SDK -> {
                    RepWriteOffDataBean(platform, RepWriteOffYch(codeData, channel, 1))
                }
                BackstagePlatform.KKB -> {
                    RepWriteOffDataBean(platform, RepWriteOffKkb(codeData, channel, 1))
                }
            }
        }catch (e: Exception){
            e.printStackTrace()
            null
        }
    }

    override suspend fun placeLocalWithdrawalOrder(
        platform: BackstagePlatform,
        k: String,
        success: Boolean,
        money: String,
        realOutCoins: Long,
        needCoins: Long,
        isMqOrder: Boolean,
        isWriteOff: Boolean,
        isWithdrawal: Boolean,
        isCash: Boolean,
        uid: String,
    ): ReqStartResultBean? {
        return try {
            val reqData = when (platform) {
                BackstagePlatform.DEF_MQTT -> {
                    null
                }

                BackstagePlatform.LYY_SDK -> {

                    StartResultParamLyySdk(
                        if (success) 0 else 1,
                        if (success) "" else "设备故障",
                        k
                    )
                }

                BackstagePlatform.LYY_BOX -> {
                    StartResultParamLyyBox(
                        if (success) 1 else 0,
                        if (success) "" else "设备故障",
                        k
                    )
                }

                BackstagePlatform.WHM_MQTT -> {
                    null
                }

                BackstagePlatform.WHM_MQTT_HEX -> {
                    StartResultParamWhmMqttHex(
                        if (success) 1 else 2,
                        if (success) 0 else 1,
                        "",
                        k,
                        realOutCoins,
                        needCoins,
                        isWithdrawal
                    )
                }

                BackstagePlatform.YCH_SDK -> {
                    StartResultParamYch(
                        if (success) 0 else 1,
                        realOutCoins.toInt(),
                        needCoins.toInt(),
                        -1L,
                        k,
                        k,
                        isMqOrder,
                        isWriteOff
                    )
                }

                BackstagePlatform.KKB -> {
                    StartResultParamKkb(
                        isCash,
                        if (success) 0 else 1,
                        k,
                        money,
                        needCoins.toInt(),
                        realOutCoins.toInt(),
                        "",
                        -1,
                        uid
                    )
                }
            }
            ReqStartResultBean(platform, k, reqData)
        } catch (e: Exception) {
            e.printStackTrace()
            logFile("上报本地提币订单下单数据异常：${e.message}")
            null
        }
    }

    private fun createCashOrder(
        platform: BackstagePlatform,
        uuid: String,
        money: String,
        coins: String,
        moneyList: String
    ): RepCashDataBean? {
        return try {

            when (platform) {
                BackstagePlatform.DEF_MQTT -> {
                    null
                }
                BackstagePlatform.LYY_SDK -> {
                    RepCashDataBean(
                        platform,
                        RecieveOrderLyySdkBean(money, coins, uuid, uuid, true),
                        RepCashLyysdk("", "", money, coins),
                        uuid
                    )
                }

                BackstagePlatform.LYY_BOX -> null
                BackstagePlatform.WHM_MQTT -> null
                BackstagePlatform.WHM_MQTT_HEX -> {
                    val payType = 1//纸钞
                    val orderUnit = 1//个
//                    val currencyUnit = 4//元
                    val currencyUnit = CommonUtil.getCurrencyUnit(country)
                    val cashDataList: MutableList<CashDataWhmhex> = mutableListOf()
                    val moneyItems = moneyList.split(";")
                    moneyItems.forEach { item ->
                        if (item.isNotEmpty()) {
                            val moneyDatas = item.split(",")
                            val itemMoney = moneyDatas[0].toLong()/Config.CONVERSION_RATIO
                            val sum = moneyDatas[1]
                            cashDataList.add(CashDataWhmhex(
                                1,//1-纸钞 2-硬币
                                currencyUnit,//货币单位
                                itemMoney.toLong(),//面额
                                sum.toLong(),//数量
                                1,//编号
                                1//重试次数
                            ))
                        }
                    }
                    logFile("纸钞订单上报数据1：${GsonUtil.getInstance()?.toJson(cashDataList)}")
                    RepCashDataBean(
                        platform,
                        RecieveOrderWhmMqttHexBean(money, coins, uuid, uuid, true, payType, orderUnit, "0", currencyUnit),
                        RepCashWhmhex(cashDataList),
                        uuid
                    )
                }

                BackstagePlatform.YCH_SDK -> {
                    RepCashDataBean(
                        platform,
                        RecieveOrderYchBean(uuid, money, coins, uuid, uuid, true, false),
                        RepCashYch(uuid, 0, (money.toLong()/100).toString(), -1, 0, coins.toLong(), "", System.currentTimeMillis(), 0, ""),
                        uuid
                    )
                }

                BackstagePlatform.KKB -> {
                    RepCashDataBean(
                        platform,
                        RecieveOrderKkbBean(uuid, money, coins, uuid, uuid, true, false),
                        RepCashKkb(uuid, 0, money, -1, 0, coins.toLong(), "", System.currentTimeMillis(), 0, ""),
                        uuid)
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
            logFile("创建现金订单异常：${e.message}")
            null
        }
    }

    /**
     * 获取解析后的套餐数据
     * @param goodEntity 从数据库拿到的原始数据
     */
    private fun getFinalGoods(goodEntity: GoodEntity): GoodListBean? {
        return try {
            val platform = goodEntity.platform
            val goodList = goodEntity.goodDetial

            val normalList: MutableList<GoodBean> = mutableListOf()
            val rechargeList: MutableList<GoodBean> = mutableListOf()

            when (platform) {
                BackstagePlatform.DEF_MQTT -> {}
                BackstagePlatform.LYY_SDK -> {
                    val lyyGoods =
                        GsonUtil.getInstance()?.fromJson<MutableList<LyySdkGoodBean>>(
                            goodList,
                            object : TypeToken<MutableList<LyySdkGoodBean?>?>() {}.type
                        )
                    lyyGoods?.let {
                        it.forEach { item ->
                            val goodBean = GoodBean()
                            goodBean.goodId = item.id
                            goodBean.goodName = item.created
                            goodBean.money = item.money
                            goodBean.amount = item.amount
                            goodBean.platform = platform
                            when (item.type) {
                                "0" -> {
                                    goodBean.goodType = PackageType.NORMAL
                                    normalList.add(goodBean)
                                }

                                "1" -> {
                                    goodBean.goodType = PackageType.RECHARGE
                                    rechargeList.add(goodBean)
                                }
                            }
                        }
                    }
                }

                BackstagePlatform.LYY_BOX -> {}
                BackstagePlatform.WHM_MQTT -> {

                    GsonUtil.getInstance()?.fromJson<MutableList<WhmGoodBean>>(
                        goodList,
                        object : TypeToken<MutableList<WhmGoodBean?>?>() {}.type
                    )?.let {
                        it.forEach { item ->
                            val goodBean = GoodBean()
                            goodBean.goodId = item.id
                            goodBean.goodName = item.name
                            goodBean.money = item.money
                            goodBean.amount = item.amount
                            goodBean.gift = item.flag
                            goodBean.platform = platform
                            when (item.type) {
                                1 -> {
                                    goodBean.goodType = PackageType.NORMAL
                                    normalList.add(goodBean)
                                }

                                else -> {
                                    goodBean.goodType = PackageType.RECHARGE
                                    rechargeList.add(goodBean)
                                }
                            }
                        }
                    }
                }

                BackstagePlatform.YCH_SDK -> {
                    GsonUtil.getInstance()?.fromJson<MutableList<YchGoodBean>>(
                        goodList,
                        object : TypeToken<MutableList<YchGoodBean?>?>() {}.type
                    )?.let {
                        it.forEach { item ->
                            if (item.IsFault){
                                return@forEach
                            }
                            //money与realAmount 参数互换
                            val goodBean = GoodBean()
                            goodBean.goodId = item.PackageID
                            goodBean.goodName = item.PakageName
                            goodBean.money = item.Price//
                            goodBean.amount = item.Coins.toString()
                            goodBean.platform = platform
                            goodBean.realAmount = item.Price//
                            goodBean.devUnit = ""
                            goodBean.gift = item.GavingCount.toString()
                            when (item.PackageType) {
                                1 -> {
                                    goodBean.goodType = PackageType.NORMAL
                                    normalList.add(goodBean)
                                }

                                else -> {
                                    goodBean.goodType = PackageType.RECHARGE
                                    rechargeList.add(goodBean)
                                }
                            }
                        }
                    }
                }

                BackstagePlatform.KKB -> {
                    GsonUtil.getInstance()?.fromJson<MutableList<KkbGoodBean>>(
                        goodList,
                        object : TypeToken<MutableList<KkbGoodBean?>?>() {}.type
                    )?.let {
                        it.forEach { item ->
                            if (item.IsFault){
                                return@forEach
                            }
                            //money与realAmount 参数互换
                            val goodBean = GoodBean()
                            goodBean.goodId = item.PackageID
                            goodBean.goodName = item.PakageName
                            goodBean.money = item.Price//
                            goodBean.amount = item.Coins.toString()
                            goodBean.platform = platform
                            goodBean.realAmount = item.Price//
                            goodBean.devUnit = ""
                            goodBean.gift = item.GavingCount.toString()
                            when (item.PackageType) {
                                1 -> {
                                    goodBean.goodType = PackageType.NORMAL
                                    normalList.add(goodBean)
                                }

                                else -> {
                                    goodBean.goodType = PackageType.RECHARGE
                                    rechargeList.add(goodBean)
                                }
                            }
                        }
                    }
                }

                BackstagePlatform.WHM_MQTT_HEX -> {
                    GsonUtil.getInstance()?.fromJson<MutableList<WhmHexGoodBean>>(
                        goodList,
                        object : TypeToken<MutableList<WhmHexGoodBean?>?>() {}.type
                    )?.let {
                        it.forEach { item ->
                            //money与realAmount 参数互换
                            val goodBean = GoodBean()
                            goodBean.goodId = item.pkgIdHex
                            goodBean.goodName = item.pkgName
                            goodBean.money = item.pkgRealAmount//
                            goodBean.amount = item.pkgValue
                            goodBean.platform = platform
                            goodBean.goodUnit = item.pkgUnit
                            goodBean.realAmount = item.pkgAmount//
                            goodBean.devUnit = item.pkgDevUnit
                            when (item.pkgType) {
                                1 -> {
                                    goodBean.goodType = PackageType.NORMAL
                                    normalList.add(goodBean)
                                }

                                else -> {
                                    goodBean.goodType = PackageType.RECHARGE
                                    rechargeList.add(goodBean)
                                }
                            }
                        }
                    }
                }
            }
            GoodListBean(normalList, rechargeList)
        } catch (e: Exception) {
            e.printStackTrace()
            logFile("获取解析后的套餐数据异常：${e.message}")
            null
        }

    }

    /**
     * 根据进钞总额计算出币数
     * @param cashGoodBeanList 纸钞套餐
     * @param money 进钞总额
     */
    private fun calculateCoins(cashGoodBeanList: MutableList<CashGoodBean>, money: Long): Long{
        return try {
            val calculateCashGoodList = cashGoodBeanList
            //把默认的出币加入纸钞套餐，如：1元1币
            val defaultMoneyCoins = Config.DEFAULT_MONEY_COINS.split(",")
            val dMoney = defaultMoneyCoins[0].toLong()
            val dCoins = defaultMoneyCoins[1].toLong()
            var hasDefaultMoney = false
            run hasDefaultMoney@{
                calculateCashGoodList.forEach { cashGood ->
                    if (cashGood.price.toLong() == dMoney){
                        hasDefaultMoney = true
                        return@hasDefaultMoney
                    }
                }
            }
            if (!hasDefaultMoney){
                calculateCashGoodList.add(CashGoodBean("", dMoney.toString(), dCoins.toString(), "0", -1))
            }

            val cashGoodMoneyList: MutableList<Long> = mutableListOf()
            calculateCashGoodList.forEach { cashGood ->
                cashGoodMoneyList.add(cashGood.price.toLong())
            }
            //排序 升序
            cashGoodMoneyList.sortWith { u1, u2 ->
                u2.compareTo(u1)
            }

            calculation(calculateCashGoodList, cashGoodMoneyList, money)
        }catch (e: Exception){
            e.printStackTrace()
            logFile("根据进钞总额计算出币数异常：${e.message}")
            0L
        }
    }

    private fun calculation(cashGoodList: MutableList<CashGoodBean>, cashMoneyItem: MutableList<Long>, calculateMoney: Long): Long{
        return try {
            var coins = 0L
            for (i in cashMoneyItem.indices){
                val moneyItem = cashMoneyItem[i]
                if (calculateMoney >= moneyItem){
                    var targetCashGood: CashGoodBean? = null
                    cashGoodList.forEach { cashGood ->
                        if (cashGood.price.toLong() == moneyItem){
                            targetCashGood = cashGood
                            coins = (targetCashGood?.value?.toLong() ?: 0L) + (targetCashGood?.flag?.toLong() ?: 0L)
                            val remianMoney = calculateMoney - (targetCashGood?.price?.toLong() ?: 0L)
                            return coins + calculation(cashGoodList, cashMoneyItem, remianMoney)
                        }
                    }
                }
            }
            coins
        }catch (e: Exception){
            e.printStackTrace()
            0L
        }
    }


}